package com.easyCode.mysql.sqlBuilder.sqlInfo;

import com.easyCode.mysql.MysqlMappingContainer;
import com.easyCode.sqlBuilder.sqlInfo.BaseDataBaseSqlInfo;
import com.easyCode.sqlBuilder.sqlUtil.SqlBuildUtil;
import lombok.*;


/**
 * 提供数据库相关的相关sqlInfo
 * @author 大忽悠
 * @create 2022/11/8 19:22
 */
@Data
public class MysqlDataBaseSqlInfo extends BaseDataBaseSqlInfo {
    private final CharsetSqlInfo charsetSqlInfo=CharsetSqlInfo.getDefault();

    @SneakyThrows
    public MysqlDataBaseSqlInfo() {
        Class.forName(MysqlMappingContainer.class.getName());
    }

    @Override
    protected String doBuildSql() {
        //建库的上半部分sql语句
        String topHalf = SqlBuildUtil.assembler(buildCreateDataBaseSql(), buildUseSql(), buildFixedPartTopHalf());
        //数据库表组成的相关sql语句
        StringBuilder tableSql=new StringBuilder();
        tableSqlInfoList.forEach(tableSqlInfo -> tableSql.append(tableSqlInfo.buildSql()));
        //建库下半部分sql语句
        String downHalf = SqlBuildUtil.buildSqlWithSemicolon("SET FOREIGN_KEY_CHECKS = 1");
        //组装三部分
        return topHalf+tableSql+downHalf;
    }

    /**
     * 添加固定的上半部分sql语句
     */
    private String buildFixedPartTopHalf() {
       return SqlBuildUtil.assembler(SqlBuildUtil.buildSqlWithSemicolon("SET NAMES utf8mb4"),
               SqlBuildUtil.buildSqlWithSemicolon("SET FOREIGN_KEY_CHECKS = 0"));
    }

    private String buildUseSql() {
      return SqlBuildUtil.buildSqlWithSemicolon("USE",SqlBuildUtil.wrapSqlParam(dataBaseName));
    }

    private String buildCreateDataBaseSql() {
        return createDataBase? SqlBuildUtil.buildSqlWithSemicolon("CREATE DATABASE","IF NOT EXISTS",SqlBuildUtil.wrapSqlParam(dataBaseName)):"";
    }
}
